package com.jihox.abookpro;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;

import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Caption;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.fragment.AssertFragment;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.PictureUtil;
import com.jihox.abookpro.view.ChangeSequenceGridView;
import com.jihox.abookpro.view.ChangeSequenceGridView.OnReorderItemsListener;
import com.jihox.abookpro.view.JHProgressDialog;

public class ChangeSequenceActivity extends BaseActivity {

	private ChangeSequenceGridView gridView;
	private Button btnBack;
	private Button btnSave;
	private Button btnChangeSequence;
	private Button btnReset;
	private Vector<Page> pages;
	private List<Integer> pageIndex = null;
	private List<Bitmap> images = null;
	private ChangeSequenceAdapter adapter;
	private AssertFragment assertFragment;
	private SoftReference<Drawable> fontSpineDrawable;
	private SoftReference<Drawable> backSpineDrawable;
	private JHProgressDialog pd;
	private BookProject bookProject;
	private MyApplication myApplication = null;
	private boolean isChangeSequenceNeedAssert;
	private JHProgressDialog savepd;
	private String templateName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_sequence);
		myApplication = MyApplication.getInstance();
		bookProject = myApplication.getBookProject();
		templateName = bookProject.getBook().getTemplateName();
		pages = bookProject.getBook().getPages();
		pd = JHProgressDialog.show(this, null,
				getResources().getString(R.string.T_Loading_short));
		new Thread(new Runnable() {

			@Override
			public void run() {
				pageIndex = getPageIndexList();
				images = getPageImages(pageIndex);
				mHandler.sendEmptyMessage(0);
			}
		}).start();
		
		initView();
		setOnClick();

	}
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
			switch(msg.what){
			case 0:
				pd.dismiss();
				setApdapter();
				SharedPreferences preferences = getSharedPreferences(
						"assert_pref", Context.MODE_APPEND);
				isChangeSequenceNeedAssert = preferences.getBoolean("isChangeSequenceNeedAssert", true);
				if(isChangeSequenceNeedAssert){
					WindowManager wm = (WindowManager)MyApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
					int widthScreen = wm.getDefaultDisplay().getWidth();
					int heightScreen = wm.getDefaultDisplay().getHeight();
					assertFragment=new AssertFragment(3,widthScreen/2,heightScreen/2,widthScreen/8+10);
					getFragmentManager().beginTransaction().add(R.id.layout_container, assertFragment).commit();
					isChangeSequenceNeedAssert=false;
				}
				break;
			case 1:
				savepd.dismiss();
				backMethod(1);
				break;
			}
		}
	};

	
	
	/**
	 * 获得内页图
	 */
	private List<Bitmap> getPageImages(List<Integer> indexs) {
		
		final List<Bitmap> images = new ArrayList<Bitmap>();
		for (int i = 0; i < indexs.size(); i++) {
			int index = indexs.get(i);
			if (index % 2 == 0){
				images.add(loadBitmapWithCache(index));
			}else{
				Bitmap bitmap = loadBitmapWithCache(index).copy(Bitmap.Config.RGB_565, true);
				Matrix matrix = new Matrix();
				float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
						0.0f, 0.0f, 1.0f };
				matrix.setValues(values);
				bitmap = Bitmap.createBitmap(bitmap, 0, 0,
						bitmap.getWidth(),
						bitmap.getHeight(), matrix, true);
				images.add(bitmap);
			}
			
		}
		
		return images;

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		backMethod(0);
	}

	private void backMethod(int resultCode) {
		Intent intent = new Intent();
		intent.setClass(ChangeSequenceActivity.this, CurlActivity.class);

		ChangeSequenceActivity.this.setResult(resultCode, intent);
		this.finish();
	}
	
	/**
	 * 设置适配器
	 */
	private void setApdapter() {
		adapter = new ChangeSequenceAdapter(ChangeSequenceActivity.this, images);
		gridView.setAdapter(adapter);
		gridView.setOnReorderItemsListener(new OnReorderItemsListener() {
			
			@Override
			public void reorderItems(int from, int to) {
				System.out.println("reorderItems from:" + from + " to:" + to);
				//这里的处理需要注意下
				if(from < to){
					for(int i=from-1; i<to-1; i++){
						Collections.swap(pageIndex, i, i+1);
					}
				}else if(from > to){
					for(int i=from-1; i>to-1; i--){
						Collections.swap(pageIndex, i, i-1);
					}
				}

				images = getPageImages(pageIndex);
				adapter.setImages(images);
				//设置新到的item隐藏，不用调用notifyDataSetChanged来刷新界面，因为setItemHide方法里面调用了
				adapter.setHideItem(-1);
			}
		});
	}

	/**
	 * 控件事件
	 */
	private void setOnClick() {
		// gridView.setAdapter(adapter);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				backMethod(0);
			}
		});
		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				savepd = JHProgressDialog.show(ChangeSequenceActivity.this, null, "正在保存页码顺序...");
				Vector<Page> newPages = new Vector<Page>();

				boolean isRegularPage =false;
				int regularPageCnt = 0;
				for (int i=0;i< pages.size();i++) {
					Page page = pages.get(i);
					if (page.getType() == Page.REGULAR) {
						List<PagePicture> pictures = page.getPictures();
						if (pictures!=null){
							for (PagePicture pagePicture : pictures) {
								if (!pagePicture.isClipart()) {
									isRegularPage = true;
									break;
								}
							}
						}
						if (isRegularPage) {
							Page newPage = pages.get(pageIndex.get(regularPageCnt));
							newPage.setNeedRedraw(true);
							newPages.add(newPage);

							regularPageCnt++;
							isRegularPage = false;
						}else{
							newPages.add(page);
						}
					}else{
						newPages.add(page);
					}
				}
				bookProject.getBook().setPages(newPages);
				mHandler.sendEmptyMessageDelayed(1,1500);
//				backMethod(1);
			}
		});
		btnChangeSequence.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				 
				 Collections.shuffle(pageIndex);
				 images = getPageImages(pageIndex);
				 adapter.setImages(images);
				 adapter.notifyDataSetChanged();
			}
		});
		btnReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				 pageIndex = getPageIndexList();
				 images = getPageImages(pageIndex);
				 adapter.setImages(images);
				 adapter.notifyDataSetChanged();
			}
		});

	}

	/**
	 * 控件初始化
	 */
	private void initView() {
		gridView = (ChangeSequenceGridView) findViewById(R.id.gridview);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnSave = (Button) findViewById(R.id.btnSave);
		btnChangeSequence = (Button) findViewById(R.id.btnChangeSequence);
		btnReset = (Button) findViewById(R.id.btnReset);
		 
	}

	/**
	 * GridView适配器
	 */
	public class ChangeSequenceAdapter extends BaseAdapter {

		private List<Bitmap> images;
		private LayoutInflater inflater;
		private int mHidePosition = -1;
		
		public ChangeSequenceAdapter(Context context, List<Bitmap> images) {
			inflater = LayoutInflater.from(context);
			this.images = images;
		}
		
		public void setHideItem(int hidePosition){
			this.mHidePosition = hidePosition; 
			this.notifyDataSetChanged();
		}

		public void setImages(List<Bitmap> images){
			this.images =images;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return images.size()+1;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return images.get(position-1);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position-1;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.gridview_item, null);
				viewHolder = new ViewHolder();
				viewHolder.image = (com.jihox.abookpro.view.ShowPhotoImageView) convertView
						.findViewById(R.id.image);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			if (position==0){
				viewHolder.image.setBackgroundColor(android.graphics.Color.parseColor("#00ffffff"));
			}else{
				viewHolder.image.setImageBitmap(images.get(position-1));
			}
			
//			if(position == mHidePosition){
//				convertView.setVisibility(View.INVISIBLE);
//			}
//			
			return convertView;
		}

		private class ViewHolder {
			public com.jihox.abookpro.view.ShowPhotoImageView image;
		}

	}

	/**
	 * 获得非剪切画内页下标
	 * 
	 * @return indexs
	 */
	private List<Integer> getPageIndexList() {
		boolean isRegularPage =false;
		List<Integer> indexs = new ArrayList<Integer>();
		for (int i = 0; i < pages.size(); i++) {
			if (pages.get(i).getType() == Page.REGULAR) {
				List<PagePicture> pictures = pages.get(i).getPictures();
				if (pictures==null){
					continue;
				}
				for (PagePicture pagePicture : pictures) {
					if (!pagePicture.isClipart()) {
						isRegularPage = true;
						break;
					}
				}
				if (isRegularPage) {
					indexs.add(i);
					isRegularPage = false;
				}
			}
		}
		return indexs;
	}
	
	private String getDirPath() {
		return Environment.getExternalStorageDirectory()
				+ NativeImageLoader.jihoxUrl + "/.album";
	}
	
	private String getImagePath(int index) {
		return getDirPath() + "/albumpage" + index + ".jpg";
	}

	private Bitmap loadBitmapWithCache(int index) {
		Bitmap bitmap = null;
		bitmap = NativeImageLoader.getInstance()
				.loadNativeImageSyncAndOriginal(
						getImagePath(index), false);
		
		if (bitmap == null) {
			bitmap = writeOnToSDCard(CurlActivity.imageWidth, CurlActivity.imageHeight, index, false);
		}
		
		if (bitmap.isRecycled()) {
			Bitmap b = writeOnToSDCard(300, 300, index, false);
			return b;
		}
		return bitmap;
	}

	private Bitmap writeOnToSDCard(int width, int height, int index,
			boolean returnNull) {
		// TODO Auto-generated method stub
		String path = getImagePath(index);
		Bitmap pageBitmap = loadBitmap(width, height, index);
		System.gc();
	
		FileOutputStream fos = null;
		File dir = new File(getDirPath());
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();// 创建文件夹
		}

		if (pageBitmap != null && !pageBitmap.isRecycled()) {
			try {
				fos = new FileOutputStream(path);
				pageBitmap
						.compress(Bitmap.CompressFormat.JPEG, 90, fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (Exception e) {
				pageBitmap = null;
				e.printStackTrace();
			} finally {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		// 加入MemoryCache内存中
		if (returnNull && pageBitmap != null && !pageBitmap.isRecycled()) {
			NativeImageLoader.getInstance().addBitmapToMemoryCache(path,
					pageBitmap);
			return null;
		}
		return pageBitmap;
	}
	
	// 加载翻动的压缩图片
	@SuppressWarnings("deprecation")
	private Bitmap loadBitmap(int width, int height, int index) { // TODO:写成异步预加载的，卡
		float currentScreenRealRatio = 1f;

		if (index < bookProject.getBook().getPages().size()) {
			Page currentPage = bookProject.getBook().getPages().get(index);
			if (currentPage.getType() != 0
					&& currentPage.getType() != Page.REGULAR) {
				currentScreenRealRatio = CurlActivity.coverPageScreenAndRealRatio * 0.9f;
			} else {
				currentScreenRealRatio = CurlActivity.innerPageScreenAndRealRatio * 0.9f;
			}
			height = (int) (height * 0.9);
			width = (int) (width * 0.9);
			Bitmap backgroundBitmap = Bitmap.createBitmap(width, height,
					Bitmap.Config.RGB_565);

			backgroundBitmap.eraseColor(0xFFFFFFFF);
			Canvas c = new Canvas(backgroundBitmap);
			// return backgroundBitmap;
			// 背景
			if (currentPage.getBackground() != null
					&& !currentPage.getBackground().equals("")) {
				FileInputStream ims;
				try {
					File file = new File(Environment.getExternalStorageDirectory(), ConfigProperties.getTemplatePath() +
			                 templateName + "/" + 
//							"pagecover.jpg");
			                 currentPage.getBackground().trim());
					Log.d("currentPage.getBackground()", currentPage.getBackground() + "");
					Log.d("File", file.getName() + "");
					if (Environment.getExternalStorageState().equals(
			                Environment.MEDIA_MOUNTED)) {
						try {
							ims = new FileInputStream(file);
							Drawable d;
							try {
								d = Drawable.createFromStream(ims, null);
							} catch (OutOfMemoryError e) {
								System.gc();
								System.runFinalization();
								d = Drawable.createFromStream(ims, null);
							} finally {
									ims.close();
							}
							Rect r = new Rect(0, 0, width, height);
							Paint p = new Paint();
							p.setAntiAlias(true);
							p.setColor(0xFFC0C0C0);
							c.drawRect(r, p);
							d.setBounds(r);
							d.draw(c);
							d.setCallback(null);
							BitmapDrawable bd = (BitmapDrawable) d;
							if (!bd.getBitmap().isRecycled()) {
								bd.getBitmap().recycle();
							}
							
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
			         }else {
			
					 }
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 图片s
			if (currentPage.getPictures() != null
					&& currentPage.getPictures().size() > 0) {
				for (PagePicture pagePicture : currentPage.getPictures()) {
					if (pagePicture.getImage() != null
							&& (pagePicture.getImage().getPath() != null && !pagePicture
									.getImage().getPath().equals(""))) {
						String path = pagePicture.getImage().getPath();
						// mPoint 这里用作记录所需要的图片大小
						Point mPoint = new Point(width * 2, height * 2);
						Bitmap photo = null;
						BitmapDrawable d = null;
						if (pagePicture.isClipart()) {
							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inPreferredConfig = Config.RGB_565;
							photo = PictureUtil
									.getThumbFromSDcard(
											getApplicationContext(),
											ConfigProperties.getTemplatePath() +
							                templateName + "/" +
											path.trim(),
											(int) (pagePicture.getHolder()
													.getWidth() ),
											(int) (pagePicture.getHolder()
													.getHeight()));
							d = new BitmapDrawable(photo);

						} else {
							photo = NativeImageLoader.getInstance()
									.loadNativeImageSync(path.trim(),
											mPoint, false);
							// 加载出错 绘制提醒字体
							if (photo == null) {
					
								photo = Bitmap.createBitmap(mPoint.x,
										mPoint.y, Config.RGB_565);
								photo.eraseColor(Color.WHITE);
								Canvas pc = new Canvas(photo);
								Paint paint = new Paint(
										Paint.ANTI_ALIAS_FLAG);
								paint.setAntiAlias(true);
								paint.setStrokeWidth(3);
								// TODO: 字体大小有待调查
								paint.setTextSize((float) (80));// 设置字体大小

								String text = getResources().getString(
										R.string.No_Picture_Warning);
								paint.setColor(Color.RED);
								paint.setTextAlign(Paint.Align.CENTER);
								pc.drawText(text, mPoint.x / 2 - 10,
										mPoint.y / 2, paint);
								pc.save();
							}
							
							d = new BitmapDrawable(photo);
						}

						float pointX = pagePicture.getHolder().getX()
								* currentScreenRealRatio;
						float pointY = pagePicture.getHolder().getY()
								* currentScreenRealRatio;
						float pointX1 = pointX
								+ pagePicture.getHolder().getWidth()
								* currentScreenRealRatio;
						float pointY1 = pointY
								+ pagePicture.getHolder().getHeight()
								* currentScreenRealRatio;
						Rect r = new Rect(Math.round(pointX),
								Math.round(pointY), Math.round(pointX1),
								Math.round(pointY1));
						Paint p = new Paint();
						p.setAlpha(0);
						c.drawRect(r, p);
						p.setAntiAlias(true);
						p.setFilterBitmap(true);
						d.setBounds(r);
						d.setFilterBitmap(true);
						try{
							d.draw(c);
						}catch(Exception e){
							
						}
						
						c.setDrawFilter(new PaintFlagsDrawFilter(0,
								Paint.ANTI_ALIAS_FLAG
										| Paint.FILTER_BITMAP_FLAG));

						if (pagePicture.isClipart() && photo != null
								&& !photo.isRecycled()) {
							photo.recycle();
						}
						d.setCallback(null);
						if (!d.getBitmap().isRecycled()) {
							d.getBitmap().recycle();
						}
						photo = null;
					}
				}
			}
			Rect targetRect = null;
			// captions
			if (currentPage.getCaptions() != null
					&& currentPage.getCaptions().size() > 0) {
				for (Caption caption : currentPage.getCaptions()) {
					float pointX = caption.getX() * currentScreenRealRatio;
					float pointY = caption.getY() * currentScreenRealRatio;
					float pointX1 = pointX + caption.getWidth()
							* currentScreenRealRatio;
					float pointY1 = pointY + caption.getHeight()
							* currentScreenRealRatio;
					targetRect = new Rect(Math.round(pointX),
							Math.round(pointY), Math.round(pointX1),
							Math.round(pointY1));

					Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
					paint.setAntiAlias(true);
					paint.setStrokeWidth(3);
					
					paint.setTextSize((float) (caption.getFont().getSize()
							* currentScreenRealRatio / 2.85));// 设置字体大小
					// android默认字体有：monospace sans serif
					Typeface typeface;
					if (caption.getFont().getName().startsWith("fonts/")) {
						try {
							typeface = Typeface.createFromAsset(
									this.getAssets(), caption
											.getFont().getName());
						} catch (Exception ex) {
							typeface = Typeface.create(caption.getFont()
									.getName(), caption.getFont()
									.getStyle());
						}
					} else {
						typeface = Typeface.create(caption.getFont()
								.getName(), caption.getFont().getStyle());
					}
					paint.setTypeface(typeface);// 设置字体类型
					FontMetricsInt fontMetrics = paint.getFontMetricsInt();
					int baseline = targetRect.top
							+ (targetRect.bottom - targetRect.top
									- fontMetrics.bottom + fontMetrics.top)
							/ 2 - fontMetrics.top;

					String text = caption.getText();
					if (caption.isShowTempText()){
						text = caption.getTempText();
					}
					if (text == null || text.isEmpty()) {
						text = caption.getPlaceHolder();
						if (text == null) {
							text = "";
						} else {
							if (!text.isEmpty()) {
								paint.setColor(Color.LTGRAY);
							}
						}
					} else {
						if (!currentPage.isBackCover()) {
//							text = getDrawTextString(text, paint, pointX1
//									- pointX);
						}
						paint.setColor(Color.rgb(caption.getColor()
								.getRed(), caption.getColor().getGreen(), 
								caption.getColor().getBlue()));
					}
					if (caption.getDocAlign() == Caption.ALIGN_RIGHT) {
						paint.setTextAlign(Paint.Align.RIGHT);
						c.drawText(text, targetRect.right, baseline, paint);
					} else if (caption.getDocAlign() == Caption.ALIGN_LEFT) {
						paint.setTextAlign(Paint.Align.LEFT);
						c.drawText(text, targetRect.left, baseline, paint);
					} else {
						paint.setTextAlign(Paint.Align.CENTER);
						c.drawText(text, targetRect.centerX(), baseline,
								paint);
					}
				}
			}
			// 正反面有不同的处理，1.反面的需要对称。2.所以反面的innerspine贴图位置正好要相反
			Rect spine;
			Paint p = new Paint();
			p.setColor(0xFFC0C0C0);
			int spineWidth = (int) (width * 0.05);
			int spineHeight = (int) (height * 0.05);
			if (index % 2 != 0) {
				Drawable spineDrawable = null;
				if (backSpineDrawable == null) {
					spineDrawable = PictureUtil.getDrawableFromAssetsFile(
							getApplicationContext(), "product-pid-"
									+ bookProject.getBook().getProduct()
											.getPid()
									+ "/album_spine_back.png");
					backSpineDrawable = new SoftReference<Drawable>(
							spineDrawable);
				} else {
					spineDrawable = backSpineDrawable.get();
					if (spineDrawable == null) {
						spineDrawable = PictureUtil
								.getDrawableFromAssetsFile(
										getApplicationContext(),
										"product-pid-"
												+ bookProject.getBook()
														.getProduct()
														.getPid()
												+ "/album_spine_back.png");
						backSpineDrawable = new SoftReference<Drawable>(
								spineDrawable);
					}
				}
				Bitmap dstbmp = null;
				if (bookProject.getBook().getProduct().getCategory() == 1) {
					if (currentPage.getType() == Page.REGULAR) {
						spine = new Rect();
						spine.left = width - spineWidth;
						spine.top = 0;
						spine.right = width;
						spine.bottom = height;
						c.drawRect(spine, p);
						spineDrawable.setBounds(spine);
						spineDrawable.draw(c);
					}
					Matrix matrix = new Matrix();
					float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
							0.0f, 0.0f, 1.0f };
					matrix.setValues(values);
					dstbmp = Bitmap.createBitmap(backgroundBitmap, 0, 0,
							backgroundBitmap.getWidth(),
							backgroundBitmap.getHeight(), matrix, true);
					// 回收内存
					backgroundBitmap.recycle();
					currentPage.setNeedRedraw(false);
					return dstbmp;
				} else {
					spine = new Rect();
					spine.left = 0;
					spine.top = 0;
					spine.right = width;
					spine.bottom = spineHeight;
					c.drawRect(spine, p);
					spineDrawable.setBounds(spine);
					spineDrawable.draw(c);

					Matrix matrix = new Matrix();
					float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
							0.0f, 0.0f, 1.0f };
					matrix.setValues(values);
					dstbmp = Bitmap.createBitmap(backgroundBitmap, 0, 0,
							backgroundBitmap.getWidth(),
							backgroundBitmap.getHeight(), matrix, true);
					// 回收内存
					backgroundBitmap.recycle();
					currentPage.setNeedRedraw(false);
					return dstbmp;
				}
			} else {
				Drawable spineDrawable = null;
				if (fontSpineDrawable == null) {
					spineDrawable = PictureUtil.getDrawableFromAssetsFile(
							getApplicationContext(), "product-pid-"
									+ bookProject.getBook().getProduct()
											.getPid()
									+ "/album_spine_front.png");
					fontSpineDrawable = new SoftReference<Drawable>(
							spineDrawable);
				} else {
					spineDrawable = fontSpineDrawable.get();
					if (spineDrawable == null) {
						spineDrawable = PictureUtil
								.getDrawableFromAssetsFile(
										getApplicationContext(),
										"product-pid-"
												+ bookProject.getBook()
														.getProduct()
														.getPid()
												+ "/album_spine_front.png");
						fontSpineDrawable = new SoftReference<Drawable>(
								spineDrawable);
					}
				}

				if (bookProject.getBook().getProduct().getCategory() == 1) {
					if (currentPage.getType() == Page.REGULAR) {
						spine = new Rect();
						spine.left = 0;
						spine.top = 0;
						spine.right = spineWidth;
						spine.bottom = height;
						c.drawRect(spine, p);
						spineDrawable.setBounds(spine);
						spineDrawable.draw(c);
					}
					currentPage.setNeedRedraw(false);
					return backgroundBitmap;
				} else {
					spine = new Rect();
					spine.left = 0;
					spine.top = 0;
					spine.right = width;
					spine.bottom = spineHeight;
					c.drawRect(spine, p);
					spineDrawable.setBounds(spine);
					spineDrawable.draw(c);
					currentPage.setNeedRedraw(false);
					return backgroundBitmap;
				}
			}
			
		} else {
			return Bitmap
					.createBitmap(width, height, Bitmap.Config.RGB_565);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(isChangeSequenceNeedAssert){
				getFragmentManager().beginTransaction().remove(assertFragment).commit();
				SharedPreferences preferences = this.getSharedPreferences(
						"assert_pref", Context.MODE_APPEND);
				Editor editor = preferences.edit();
				editor.putBoolean("isChangeSequenceNeedAssert", false);
				editor.commit();
				isChangeSequenceNeedAssert=false;
			}else{
				backMethod(0);
			}
		}
		return false;
	}

}
